#!/usr/bin/env python

from opencv import *
import sys

class histogram(object):
	def __init__(self, image):
		range_0=[0,256]
		ranges = [ range_0 ]
		self.hist_size = 64
		self.src_image=image
		self.dst_image=cvCloneImage(image)
		self.hist_image=cvCreateImage(cvSize(320,200), 8, 1)
		self.hist=cvCreateHist([self.hist_size], CV_HIST_ARRAY, ranges, 1)
		self.lut=cvCreateMat(256,1,CV_8U)

	def showHist(self):
		cvNamedWindow("image", 0);
		cvNamedWindow("histogram", 0);
		
		brightness = 0;
		contrast = 0;
		max_value = 0;

		delta = -128.*contrast/100;
		a = (256.-delta*2)/255.;
		b = a*brightness + delta;

		for i in range(256):
			v = cvRound(a*i + b);
			if( v < 0 ):
				v = 0;
			if( v > 255 ):
				v = 255;
			self.lut[i] = v;
		
		cvLUT( self.src_image, self.dst_image, self.lut );
		cvShowImage( "image", self.dst_image );

		cvCalcHist( [self.dst_image], self.hist, 0, None );
		cvZero( self.dst_image );
		min_value, max_value = cvGetMinMaxHistValue( self.hist );
		hbins = self.hist.bins[0]
		cvScale( hbins, hbins, float(self.hist_image.height)/max_value, 0 );
		#cvNormalizeHist( hist, 1000 );

		cvSet( self.hist_image, cvScalarAll(255));
		bin_w = cvRound(float(self.hist_image.width)/self.hist_size);

		histData = []
		for i in range(self.hist_size):
			count = cvRound(cvGetReal1D(hbins,i))
			cvRectangle( self.hist_image, cvPoint(i*bin_w, self.hist_image.height),
						 cvPoint((i+1)*bin_w, self.hist_image.height - count),
						 cvScalarAll(0), -1, 8, 0 );
			if count > 5:
				histData.append((i, count))

		cvShowImage("histogram", self.hist_image)
		cvWaitKey(0)

		return histData

	def getHist(self):
		brightness = 0;
		contrast = 0;
		max_value = 0;

		delta = -128.*contrast/100;
		a = (256.-delta*2)/255.;
		b = a*brightness + delta;

		for i in range(256):
			v = cvRound(a*i + b);
			if( v < 0 ):
				v = 0;
			if( v > 255 ):
				v = 255;
			self.lut[i] = v;
		
		cvLUT( self.src_image, self.dst_image, self.lut );

		cvCalcHist( [self.dst_image], self.hist, 0, None );
		cvZero( self.dst_image );
		min_value, max_value = cvGetMinMaxHistValue( self.hist );
		hbins = self.hist.bins[0]
		cvScale( hbins, hbins, float(self.hist_image.height)/max_value, 0 );
		#cvNormalizeHist( hist, 1000 );

		cvSet( self.hist_image, cvScalarAll(255));
		bin_w = cvRound(float(self.hist_image.width)/self.hist_size);

		histData = []
		for i in range(self.hist_size):
			count = cvRound(cvGetReal1D(hbins,i))
			if count > 5:
				histData.append((i, count))
		return histData
